import os,math ;
from PyQt4.QtCore import QObject,pyqtSignal
from KDataBase.KQueryDB import KQueryDB

class KSingleStockDataProcessor(QObject):
	'''class to help KSingleStock to process data including crop, resampling and so on'''
	def __init__(self,parent=None):
		QObject.__init__(self)	
		
	@staticmethod		
	def SampleDataByPeriod(data,period):
		# filter data with period 
		results=[[],[]]
		for index in range(0,len(data[0]),period):
			startindex=index
			endindex=min(index+period-1,len(data[0])-1)
			date=data[0][endindex]
			pblocks=data[1][startindex:endindex+1]
			pblocks=zip(*pblocks)
			newblock=[pblocks[0][0],max(pblocks[1]),min(pblocks[2]),pblocks[3][-1],sum(pblocks[4])]
			results[0].append(date)
			results[1].append(newblock)
		return results # compute the downsampled data, to polish with numpy	
	@staticmethod
	def CropDataByRange(data,timerange):
		# filter data within the timerange
		if timerange is not  None:
			curdates=data[0]
			maxindex=len(curdates)-1;
			minindex=0
			for index in range(0,len(curdates)):
				curdate=curdates[index]
				if curdates[index]>=timerange[0]:
					minindex=index;
					break;
			for index in range(len(curdates)-1,-1,-1):
				curdate=curdates[index]
				if curdates[index]<=timerange[1]:
					maxindex=index;
					break;
			result=[x[minindex:maxindex+1] for x in data]
			return result	
		else:
			return data	
	
